package org.hilo.boot.core.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.hilo.boot.core.UT;

/**
 * 
 * @author zollty
 * @since 2019年4月29日
 */
public class AjaxAccessControlFilter extends AbstractAccessControlFilter {
    
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        // If the subject isn't identified, redirect to login URL
        if (subject.getPrincipal() == null) {
            handleNotLogin(request, response);
        } else {
            handleUnauthorized(request, response);
        }
        return false;
    }

    protected void handleNotLogin(ServletRequest request, ServletResponse response) throws Exception {
        if (AjaxLoginHelper.isAjaxRequest((HttpServletRequest) request)) {
            WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        String loginUrl = getLoginUrl();
        if(UT.Str.isNotEmpty(loginUrl)) {
            saveRequestAndRedirectToLogin(request, response);
        }
    }

    protected void handleUnauthorized(ServletRequest request, ServletResponse response) throws Exception {
        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN);
    }

}
